<template>
  <div class="contents-container">
    <div class="search-area">
      <el-button size="mini" class="ml-15" type="success" @click="addData">新增</el-button>
    </div>
    <!-- 列表 -->
    <el-table :data="listData" border fit highlight-current-row style="width: 100%;">
      <el-table-column label="轮播标题" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.imgDesc }}</span>
        </template>
      </el-table-column>
      <el-table-column label="轮播图片" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-image contain :src="$urlHost+scope.row.imgUrl" :preview-src-list="srcList" alt="" @click="gteImgList($urlHost+scope.row.imgUrl)" />
        </template>
      </el-table-column>
      <el-table-column label="轮播顺序" align="center" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.carouselRank }}</span>
        </template>
      </el-table-column>
      <el-table-column label="动作类型" align="center" width="160">
        <template slot-scope="scope">
          <span>{{ scope.row.actionType==0?"无动作":scope.row.actionType==1?"跳转案例":"" }}</span>
        </template>
      </el-table-column>
      <!-- 		  <el-table-column label="关联案例名称">
        <template slot-scope="scope">
          <span>{{ scope.row.caseName }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="状态" align="center" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.flag ==0?'隐藏':'上架' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="240" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleGetDetail(scope.row.id)">修改</el-button>
          <el-button v-show="scope.row.flag ==0" type="primary" size="mini" @click="getDetail(scope.row)">上架
          </el-button>
          <el-button v-show="scope.row.flag ==1" type="primary" size="mini" @click="getDetail(scope.row)">隐藏
          </el-button>
          <el-button size="mini" type="danger" @click="handleDeleted(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page-index.sync="listQuery.page"
      :page-size.sync="listQuery.limit"
      @pagination="getListData(listQuery.page)"
    />
    <!-- 新增/修改 -->
    <PopWindow v-show="showForm" :title="title" :mode="modeValue" @close="closeForm" @addHandle="addHandle" @updateHandle="updateHandle">
      <el-form ref="formData" :model="formData" label-width="100px" size="small" :rules="formRules">
        <el-form-item label="轮播名称" prop="imgDesc">
          <el-input v-model="formData.imgDesc" class="my-input" />
        </el-form-item>
        <el-form-item label="轮播图片" prop="imgUrl">
          <el-upload
            class="avatar-uploader"
            :action="$uploadImg"
            :show-file-list="false"
            :with-credentials="true"
            name="files"
            accept="image/png, image/jpeg"
            :on-success="handleLisenceSuccess"
            :before-upload="beforeUpload"
          >
            <img v-if="formData.imgUrl" :src="$urlHost + formData.imgUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" style="border: 1px dashed #d9d9d9;" />
            <el-tooltip class="item" effect="dark" content="只能上传jpg/png文件，且不超过10MB" placement="top">
              <i class="el-icon-question" />
            </el-tooltip>
          </el-upload>
        </el-form-item>
        <el-form-item label="轮播状态" prop="flag">
          <el-switch v-model="formData.flag" active-text="上架" inactive-text="隐藏" />
        </el-form-item>
        <el-form-item label="动作类型" prop="actionType">
          <el-select v-model="formData.actionType" placeholder="请选择动作类型">
            <el-option v-for="item in typeList" :key="item.SubNum" :label="item.SubName" :value="item.SubNum" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="formData.actionType == 1" label="关联案例" prop="remark">
          <el-select v-model="formData.remark" placeholder="请选择关联案例" style="width: 100%;">
            <el-option v-for="item in caseList" :key="item.id" :label="item.title" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="轮播排序" prop="carouselRank">
          <el-input v-model="formData.carouselRank" class="my-input" />
        </el-form-item>
      </el-form>

    </PopWindow>
  </div>
</template>

<script>
	import PopWindow from '@/components/PopWindow'
	import Pagination from '@/components/Pagination'
	import {
		addCarousel,
		editCarousel,
		deleteCarousel,
		getCarouselList,
		getCarouselDetail
	} from '@/api/carousel'
	import {
		getCaseList
	} from '@/api/case'
	export default {
		name: 'Carousel',
		components: {
			PopWindow,
			Pagination
		},
		data() {
			return {
				total: 0, // 总数
				listData: [],
				listQuery: {
					page: 1, // 当前页码
					limit: 5 // 每页数量
				},
				typeList: [{
						SubName: '跳转案例',
						SubNum: 1
					},
					{
						SubName: '无动作',
						SubNum: 0
					}
				],
				caseList: [],
				showForm: false, // 新增修改弹窗显示否
				dialogStatus: '', // 弹窗状态
				title: '轮播新增',
				modeValue: 'add',
				licenceImg: '',
				srcList: [],
				formData: {
					imgDesc: '', // 轮播描述
					imgUrl: '', // 图片地址
					actionType: '', // 动作类型
					flag: 0, // 轮播图片显示顺序
					carouselRank: 1, // 上下架
					remark: '' // 备注
				},
				// 表单验证规则
				formRules: {
					imgDesc: [{
							required: true,
							message: '请输入轮播名称',
							trigger: 'blur'
						},
						{
							max: 50,
							message: '轮播名称50个字内',
							trigger: 'blur'
						}
					],
					imgUrl: [{
						required: true,
						message: '请上传轮播图片',
						trigger: 'blur'
					}],
					actionType: {
						required: true,
						message: '请选择动作类型',
						trigger: 'change'
					}
				}
			}
		},
		mounted() {
			this.getListData()
			this.getCaseSelect()
		},
		methods: {
			getListData(page) {
				var that = this
				that.$loadings()
				that.listQuery.page = page || 1
				getCarouselList(that.listQuery).then((data) => {
					that.$loadings().close()
					that.listData = data.data
					that.total = data.count
				}).catch(() => {
					that.$loadings().close()
				})
			},
			getCaseSelect() {
				const that = this
				that.$loadings()
				getCaseList({
					page: 1, // 当前页码
					limit: 999 // 每页数量
				}).then((res) => {
					that.$loadings().close()
					that.caseList = res.data
				}).catch(() => {
					that.$loadings().close()
				})
			},
			resetTemp() {
				this.title = ''
				this.formData = {
					imgDesc: '', // 轮播描述
					actionType: 0, // 动作类型
					imgUrl: '',
					flag: 0,
					carouselRank: 0, // 轮播图片显示顺序
					remark: '' // 备注
				}
			},
			research() {
				this.listQuery = {
					page: 1, // 当前页码
					limit: 5, // 每页数量
					strKey: '' // 关键字
				}
				this.getListData()
			},
			addData() {
				this.resetTemp()
				this.title = '轮播新增'
				this.modeValue = 'add'
				this.showForm = true
				this.$nextTick(() => {
					this.$refs['formData'].clearValidate()
				})
			},
			addHandle() {
				var that = this
				that.$refs.formData.validate(valid => {
					if (valid) {
						that.formData.flag = that.formData.flag ? 1 : 0
						that.$loadings()
						addCarousel(that.formData)
							.then(data => {
								that.$loadings().close()
								that.$message({
									type: 'success',
									message: '添加成功!'
								})
								that.getListData()
								that.closeForm() // 重置表单
							})
							.catch(() => {
								that.$loadings().close()
							})
					} else {
						return false
					}
				})
				this.showForm = false
			},
			closeForm() {
				this.showForm = false
			},
			handleGetDetail(id) {
				const that = this
				that.$loadings()
				getCarouselDetail(id).then((res) => {
					that.$loadings().close()
					that.formData = {
						id: res.data.id,
						imgDesc: res.data.imgDesc,
						actionType: res.data.actionType,
						imgUrl: res.data.imgUrl,
						flag: res.data.flag === 1,
						carouselRank: res.data.carouselRank,
						remark: res.data.remark
					}
					that.title = '轮播修改'
					that.modeValue = 'edit'
					that.showForm = true
				}).catch((err) => {
					that.$loadings().close()
					console.log(err)
				})
			},
			updateHandle() {
				var that = this
				that.$refs.formData.validate(valid => {
					if (valid) {
						that.formData.flag = that.formData.flag ? 1 : 0
						that.$loadings()
						editCarousel(that.formData)
							.then(data => {
								that.$loadings().close()
								that.$message({
									type: 'success',
									message: '操作成功!'
								})
								that.research()
								that.closeForm() // 重置表单
							})
							.catch(error => {
								that.closeForm() // 重置表单
								that.$loadings().close()
								console.log(error)
							})
					} else {
						return false
					}
				})
			},

			gteImgList(url) {
				this.srcList = []
				this.srcList.push(url)
			},
			getDetail(row) {
				const that = this
				that.formData = {
					id: row.id,
					imgDesc: row.imgDesc,
					actionType: row.actionType,
					imgUrl: row.imgUrl,
					flag: row.flag,
					carouselRank: row.carouselRank,
					remark: row.remark
				}
				that.formData.flag = that.formData.flag ? 0 : 1
				that.$loadings()
				editCarousel(that.formData)
					.then(data => {
						that.$loadings().close()
						that.$message({
							type: 'success',
							message: '操作成功!'
						})
						that.research()
						that.closeForm() // 重置表单
					})
					.catch(error => {
						that.$loadings().close()
						that.closeForm() // 重置表单
						console.log(error)
					})
			},
			handleDeleted(id) {
				const that = this
				that.$confirm('是否删除该条数据?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
					.then(() => {
						that.$loadings()
						deleteCarousel({
							id: id
						}).then((res) => {
							that.$loadings().close()
							that.$message({
								type: 'success',
								message: '操作成功!'
							})
							that.getListData()
						}).catch(() => {
							that.$loadings().close()
						})
					})
			},
			// 图片上传成功回调
			handleLisenceSuccess(res, file) {
				this.imgLoding.close()
				this.$message({
					type: 'success',
					message: '上传成功!'
				})
				this.uploadImg = this.$urlHost + res.data[0] // 前台展示 绝对路径
				this.formData.imgUrl = res.data[0] // 后台接受 相对路径
			},
			// 图片上传前回调
			beforeUpload(file) {
				this.imgLoding = this.$loading({
					lock: true,
					text: '图片上传中···',
					spinner: 'el-icon-loading',
					background: 'rgba(255, 255, 255, 0.4)'
				})
				const isPNG = file.type === 'image/png'
				const isJPG = file.type === 'image/jpeg'
				const isLt2M = file.size / 1024 / 1024 < 10

				if (!isPNG && !isJPG) {
					this.$message.error('上传图片只能是 PNG或JPG 格式!')
					this.imgLoding.close()
				}
				if (!isLt2M) {
					this.$message.error('上传图片大小不能超过 10MB!')
					this.imgLoding.close()
				}
				return (isPNG || isJPG) && isLt2M
			},
			showImg(url) {
				if (!url) {
					this.$message({
						type: 'error',
						message: '还未上传轮播图片!'
					})
				} else {
					this.$alert('<img src="' + this.$urlHost + url +
						'" style="width: 100%"><p style="text-align: center;">右击在新标签页中打开图片查看原图</p>', '轮播图片', {
							dangerouslyUseHTMLString: true,
							customClass: 'entercustom'
						})
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 80px;
		height: 60px;
		line-height: 60px;
		text-align: center;
	}

	.avatar {
		width: 150px;
		height: 100px;
	}
</style>
